#!/bin/bash
# 关闭防火墙
sudo systemctl disable firewalld
sudo systemctl stop firewalld

# 获取当前脚本所在的目录
CURRENT_DIR=$(dirname "$(realpath "$0")")

# 定义 Clash 可执行文件的路径
CLASH_EXEC="$CURRENT_DIR/clash/clash"

# 查找当前目录下的 .yaml 文件
YAML_FILE=$(find "$CURRENT_DIR" -maxdepth 1 -name "*.yaml" | head -n 1)

# 如果找到 .yaml 文件
if [ -n "$YAML_FILE" ]; then
    # 使用 awk 生成随机 6 位 secret 并插入 external-ui 行
    awk -v random_num=$((100000 + RANDOM % 900000)) -v current_path="$CURRENT_DIR" '
    /external-controller: '\''0.0.0.0:9090'\''/ {
        print;
        print "secret: " random_num;
        print "external-ui: " current_path "/clash/dashboard";
        next
    }
    {print}
    ' "$YAML_FILE" > temp && mv -f temp "$CURRENT_DIR/config.yaml"
fi

# 定义新的配置文件路径
CONFIG_FILE="$CURRENT_DIR/config.yaml"

# 创建 ~/.config/clash 目录
mkdir -p "$HOME/.config/clash"

# 复制 Country.mmdb 到 ~/.config/clash
if [ -f "$CURRENT_DIR/clash/Country.mmdb" ]; then
    echo "复制 Country.mmdb 到 $HOME/.config/clash..."
    cp "$CURRENT_DIR/clash/Country.mmdb" "$HOME/.config/clash"
else
    echo "找不到 Country.mmdb，请确保文件存在于 $CURRENT_DIR/clash 目录中。"
    exit 1
fi

# 创建或覆盖 clash.service 文件
cat <<EOF > /etc/systemd/system/clash.service
[Unit]
Description=clash service
After=network.target

[Service]
Type=simple
User=root
ExecStart=$CLASH_EXEC -f $CONFIG_FILE
Restart=on-failure

[Install]
WantedBy=multi-user.target
EOF

# 重新加载 systemd 管理的服务文件
systemctl daemon-reload
systemctl enable clash.service
systemctl start clash.service

echo "Clash service 已成功创建并启动。"

# **改进的 Shell 类型检测方法**
if [[ -n "$SHELL" ]]; then
    CURRENT_SHELL=$(basename "$SHELL")
else
    # 如果 SHELL 环境变量未定义，使用 ps 获取 shell 类型
    CURRENT_SHELL=$(ps -p $$ -o comm= | awk '{print $1}')
fi

# 输出当前检测到的 shell 类型
echo "Detected shell: $CURRENT_SHELL"

# 根据当前 shell 类型选择配置文件
if [[ "$CURRENT_SHELL" == "zsh" ]]; then
    SHELL_RC="$HOME/.zshrc"
    echo "检测到 zsh，将更新 ~/.zshrc"
elif [[ "$CURRENT_SHELL" == "bash" ]]; then
    SHELL_RC="$HOME/.bashrc"
    echo "检测到 bash，将更新 ~/.bashrc"
else
    echo "不支持的 shell ($CURRENT_SHELL)，无法自动配置代理。"
    exit 1
fi

# 定义要添加的配置内容
proxy_auto_start='# Proxy auto start'
proxy_env='export https_proxy=http://127.0.0.1:7890'
open_proxy_func='# Open proxy'
close_proxy_func='# Close proxy'

# 检查并添加代理自动启动配置
if ! grep -q "$proxy_auto_start" "$SHELL_RC"; then
    echo -e "\n$proxy_auto_start" >> "$SHELL_RC"
    echo "export https_proxy=http://127.0.0.1:7890" >> "$SHELL_RC"
    echo "export http_proxy=http://127.0.0.1:7890" >> "$SHELL_RC"
    echo "export all_proxy=socks5://127.0.0.1:7890" >> "$SHELL_RC"
    echo "已添加代理环境变量配置"
else
    echo "代理环境变量配置已存在，跳过添加"
fi

# 检查并添加开启代理函数
if ! grep -q "$open_proxy_func" "$SHELL_RC"; then
    echo -e "\n$open_proxy_func" >> "$SHELL_RC"
    echo "on() {" >> "$SHELL_RC"
    echo "    export https_proxy=http://127.0.0.1:7890" >> "$SHELL_RC"
    echo "    export http_proxy=http://127.0.0.1:7890" >> "$SHELL_RC"
    echo "    export all_proxy=socks5://127.0.0.1:7890" >> "$SHELL_RC"
    echo "    echo \"HTTP/HTTPS Proxy on\"" >> "$SHELL_RC"
    echo "}" >> "$SHELL_RC"
    echo "已添加开启代理函数"
else
    echo "开启代理函数已存在，跳过添加"
fi

# 检查并添加关闭代理函数
if ! grep -q "$close_proxy_func" "$SHELL_RC"; then
    echo -e "\n$close_proxy_func" >> "$SHELL_RC"
    echo "off() {" >> "$SHELL_RC"
    echo "    unset http_proxy" >> "$SHELL_RC"
    echo "    unset https_proxy" >> "$SHELL_RC"
    echo "    unset all_proxy" >> "$SHELL_RC"
    echo "    echo \"HTTP/HTTPS Proxy off\"" >> "$SHELL_RC"
    echo "}" >> "$SHELL_RC"
    echo "已添加关闭代理函数"
else
    echo "关闭代理函数已存在，跳过添加"
fi

# 配置 Docker 代理
echo -e "\n正在配置 Docker 代理..."
DOCKER_PROXY_DIR="/etc/systemd/system/docker.service.d"
DOCKER_PROXY_FILE="$DOCKER_PROXY_DIR/http-proxy.conf"

# 创建配置目录（如果不存在）
sudo mkdir -p "$DOCKER_PROXY_DIR"

# 定义要添加的 Docker 代理配置
docker_proxy_config="[Service]
Environment=\"HTTP_PROXY=http://127.0.0.1:7890\"
Environment=\"HTTPS_PROXY=http://127.0.0.1:7890\"
Environment=\"NO_PROXY=localhost,127.0.0.1\""

# 检查配置文件是否存在
if [ -f "$DOCKER_PROXY_FILE" ]; then
    # 检查配置是否已存在
    if grep -q "HTTP_PROXY=http://127.0.0.1:7890" "$DOCKER_PROXY_FILE"; then
        echo "Docker 代理配置已存在，跳过添加"
    else
        # 备份现有文件并添加新配置
        echo "更新 Docker 代理配置..."
        sudo cp "$DOCKER_PROXY_FILE" "${DOCKER_PROXY_FILE}.bak"
        echo "$docker_proxy_config" | sudo tee "$DOCKER_PROXY_FILE" > /dev/null
        echo "已更新 Docker 代理配置"
    fi
else
    # 创建新配置文件
    echo "创建 Docker 代理配置文件..."
    echo "$docker_proxy_config" | sudo tee "$DOCKER_PROXY_FILE" > /dev/null
    echo "已创建 Docker 代理配置"
fi

# 重新加载 systemd 并重启 Docker
echo "重新加载 systemd 配置并重启 Docker..."
sudo systemctl daemon-reload
sudo systemctl restart docker

# 检查 Docker 状态
if sudo systemctl is-active --quiet docker; then
    echo "Docker 服务已成功重启"
else
    echo "Docker 服务启动失败，请检查配置"
fi

# 提示用户手动加载配置
echo -e "\n已完成所有配置，请手动运行以下命令以应用所有更改："
echo "1. source $SHELL_RC"
echo "2. 使用 on 启用代理，使用 off 禁用代理"
echo "3. 使用 curl -I https://www.google.com 测试网络代理"
echo "4. 使用 curl -x http://127.0.0.1:7890 -I https://hub.docker.com/ 测试 Docker 代理"